package org.sun.sunshine.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServer {
    public static void main(String[] args) throws IOException{


        Selector selector=Selector.open();
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(8080));

        while(true){
            selector.select();
            selector.selectedKeys().forEach(selectionKey -> {
                if(selectionKey.isAcceptable()){
                    try {
                        SocketChannel socketChannel=serverSocketChannel.accept();
                        if(socketChannel!=null){
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.OP_READ);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }else if(selectionKey.isReadable()){
                    SocketChannel socketChannel=(SocketChannel) selectionKey.channel();
                    try {
                        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                        int len=0;
                        while((len=socketChannel.read(byteBuffer))>0){
                            byteBuffer.flip();
                            System.out.println(new String(byteBuffer.array(), 0,len));
                            byteBuffer.clear();
                        }
                    }catch (IOException e){
                        selectionKey.cancel();
                    }finally {
                        try {
                            socketChannel.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
        }
    }
}
